<template>
  <div>
    <complex-table v-loading="loading" :data="events">
      <el-table-column
        :label="$t('business.event.reason')"
        prop="reason"
        fix
        max-width="50px"
      />
      <el-table-column
        :label="$t('business.event.type')"
        prop="type"
        fix
        max-width="50px"
      >
        <template #default="{ row }">
          <el-tag v-if="row.type === 'Normal'">{{ row.type }}</el-tag>
          <el-tag v-else type="danger">{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.event.message')"
        prop="message"
        fix
        min-width="200px"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('commons.table.created_time')"
        min-width="50px"
      >
        <template #default="{ row }">
          <span>{{ row.eventTime }}</span>
        </template>
      </el-table-column>
    </complex-table>
  </div>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import { onMounted, ref, watch } from "vue";
import { useK8SApi } from "../../../api/k8s";

type Prop = {
  namespace?: string;
  cluster?: string;
  selector?: string;
};

const props = defineProps<Prop>();
const events = ref([]);
const loading = ref(false);

const { eventsRepo } = useK8SApi();

const reloadEvents = () => {
  loading.value = true;
  eventsRepo
    .listEventsWithNsSelector(props.cluster, props.namespace, props.selector)
    .then(res => {
      res.items?.forEach(item => {
        item.eventTime =
          item.eventTime || item.firstTimestamp || item.lastTimestamp;
        events.value.unshift(item);

        events.value.sort((a, b) => {
          return Date.parse(b.eventTime) - Date.parse(a.eventTime);
        });
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  reloadEvents();
});

watch(
  () => props.selector,
  () => {
    reloadEvents();
  }
);
</script>

<style scoped></style>
